﻿using System;
using System.Collections.Generic;

namespace Flux.Mvvm.Messaging
{
	public class Messenger
		: IMessenger
	{
		private readonly Dictionary<object, List<Action<object>>> _registeredActions = new Dictionary<object, List<Action<object>>>();

		public virtual void Register(Action<object> action)
		{
			Register(null, action);
		}

		public virtual void Register(object token, Action<object> action)
		{
			if (_registeredActions.ContainsKey(token))
			{
				_registeredActions[token].Add(action);
			}
			else
			{
				var list = new List<Action<object>> {action};
				_registeredActions.Add(token, list);
			}
		}

		public virtual void Send(object message)
		{
			Send(null, message);
		}

		public virtual void Send(object token, object message)
		{
			if (!_registeredActions.ContainsKey(token)) return;
			var actions = _registeredActions[token];
			foreach (var action in actions)
			{
				action.Invoke(message);
			}
		}

		public virtual void Unregister()
		{
			_registeredActions.Clear();
		}

		public virtual void Unregister(object token)
		{
			_registeredActions[token].Clear();
		}
	}
}